package com.css.zfzx.sjcj.modules.drill.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.dept.repository.entity.DeptEntity;
import com.css.bpm.platform.org.role.repository.entity.RoleEntity;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.CheckObjFields;
import com.css.zfzx.sjcj.common.utils.LocationUtil;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.drill.Entity.QhY02Entity;
import com.css.zfzx.sjcj.modules.drill.Entity.vo.*;
import com.css.zfzx.sjcj.modules.drill.base.basedivision.repository.BaseDivisionRepository;
import com.css.zfzx.sjcj.modules.drill.repository.*;
import com.css.zfzx.sjcj.modules.drill.service.*;
import com.css.zfzx.sjcj.modules.drill.viewobjects.ExportVo;
import com.css.zfzx.sjcj.modules.drill.viewobjects.QhY02QueryParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author Li Helei
 * @date 2021/1/16 10:44
 */
@Slf4j
@Service
public class QhY02ServiceImpl implements QhY02Service {

    @Autowired
    private QhY02Repository qhY02Repository;
    @Autowired
    private QhY04Repository qhY04Repository;
    @Autowired
    private QhY04Service qhY04Service;
    @Autowired
    private QhY05Repository qhY05Repository;
    @Autowired
    private QhY05Service qhY05Service;
    @Autowired
    private QhY06Repository qhY06Repository;
    @Autowired
    private QhY06Service qhY06Service;
    @Autowired
    private QhY08Repository qhY08Repository;
    @Autowired
    private QhY08Service qhY08Service;
    @Autowired
    private QhY18Repository qhY18Repository;
    @Autowired
    private QhY18Service qhY18Service;
    @Autowired
    private QhY02NativeRepository qhY02NativeRepository;

    @Autowired
    private BaseDivisionRepository baseDivisionRepository;
    @Autowired
    private MyQhRepository myQhRepository;

    @Override
    public JSONObject queryQhY02s(QhY02QueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        if (!PlatformObjectUtils.isEmpty(sort) && sort.length() > 0) {
            sort = CheckObjFields.propertyChange(sort);
        }
        Page<QhY02Entity> qhY02Page = this.qhY02NativeRepository.queryQhY02s(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(qhY02Page);
        return jsonObject;
    }

    @Override
    public JSONObject queryQhY02s(QhY02QueryParams queryParams) {
        List<QhY02Entity> qhY02List = this.qhY02NativeRepository.listQhY02s(queryParams);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", qhY02List);
        return jsonObject;
    }

    @Override
    public JSONObject queryQhY02(QhY02QueryParams queryParams) {
        List<QhY02Entity> qhY02List = this.qhY02NativeRepository.listQhY02(queryParams);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", qhY02List);
        return jsonObject;
    }


    @Override
    public QhY02Entity getQhY02(String id) {
        QhY02Entity qhY02 = this.qhY02Repository.findByIdAndIsValid(id, "1");
        return qhY02;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveQhY02(QhY02Entity qhY02) {
        JSONObject json = new JSONObject();
        String message = "添加成功";
        List<String> allCode = qhY02Repository.getAllCode();
        if (allCode.contains(qhY02.getDrillSynthesizeCode())) {
            message = "钻孔编号:" + qhY02.getDrillSynthesizeCode() + "重复！";
            json.put("message",message);
            return json;
        }
        String uuid = UUIDGenerator.getUUID();
        qhY02.setId(uuid);
        qhY02.setDataState("0");
        qhY02.setIsValid("1");
        String userId = PlatformSessionUtils.getUserId();
        if (StringUtils.isEmpty(userId)) {
            throw new RuntimeException("场地与区划采集创建数据获取用户异常！");
        }
        qhY02.setCreateUser(userId);
        qhY02.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        qhY02.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.qhY02Repository.save(qhY02);
        json.put("message",message);
        json.put("data", qhY02);
        return json;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhY02Entity updateQhY02(QhY02Entity qhY02) {
        QhY02Entity qhY02Entity = qhY02Repository.findByIdAndIsValid(qhY02.getId(), "1");
        String userId = PlatformSessionUtils.getUserId();
        if (StringUtils.isEmpty(userId)) {
            throw new RuntimeException("场地与区划采集修改数据获取用户异常！");
        }
        UpdateUtil.copyNullProperties(qhY02Entity, qhY02);
        qhY02.setUpdateUser(userId);
        qhY02.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.qhY02Repository.save(qhY02);
        return qhY02;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQhY02s(List<String> ids) {
        List<QhY02Entity> qhY02List = this.qhY02Repository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(qhY02List) && qhY02List.size() > 0) {
            for (QhY02Entity qhY02 : qhY02List) {
                qhY02.setIsValid("0");
                qhY02.setUpdateUser(PlatformSessionUtils.getUserId());
                qhY02.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                this.qhY02Repository.save(qhY02);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQh(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        this.qhY04Repository.deleteAllByDrillIdIn(idList);
        this.qhY05Repository.deleteAllByDrillIdIn(idList);
        this.qhY06Repository.deleteAllByDrillIdIn(idList);
        this.qhY08Repository.deleteAllByDrillIdIn(idList);
        this.qhY18Repository.deleteAllByDrillIdIn(idList);
        List<QhY02Entity> qhY02List = this.qhY02Repository.findAllById(idList);
        if (!PlatformObjectUtils.isEmpty(qhY02List) && qhY02List.size() > 0) {
            for (QhY02Entity qhY02 : qhY02List) {
                qhY02.setIsValid("0");
                qhY02.setUpdateUser(PlatformSessionUtils.getUserId());
                qhY02.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                this.qhY02Repository.save(qhY02);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitQhY02(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhY02Entity> qhY02List = this.qhY02Repository.findAllById(idList);
        if (!PlatformObjectUtils.isEmpty(qhY02List) && qhY02List.size() > 0) {
            for (QhY02Entity qhY02 : qhY02List) {
                this.qhY02Repository.save(qhY02);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public JSONObject dataQualityCheckAll(String ids) {
        JSONObject res = new JSONObject();
        List<String> idList = Arrays.asList(ids.split(","));
        String drillSynthesizeCode = "";//存储质检不通过的钻孔综合编号的集合，用逗号分割
        for (String id : idList) {
            //查询钻井概况
            List<QhY02Entity> qhY02List = this.qhY02Repository.findQhY02ById(id, "1");
            if (qhY02List.size() < 1) {
                continue;
            }
            for (QhY02Entity qhY02 : qhY02List) {
                //Y02表
                qhY02 = this.dataQualityCheck(qhY02);

                String drillId = qhY02.getId();
                //Y04表
                List<QhY04Vo> qhY04VoList = qhY04Service.dataQualityCheck(drillId);
                if (!qhY04VoList.isEmpty() && qhY04VoList.size() > 0) {
                    for (QhY04Vo qhY04Vo : qhY04VoList) {
                        if (qhY04Vo.getDataState() == "1" && qhY02.getDataState() == "1") {
                            //qhY02.setDataState(qhY04Vo.getDataState());
                            qhY02.setQualityOpinion(qhY02.getQualityOpinion() + qhY04Vo.getQualityOpinion());
                            continue;
                        } else if (qhY04Vo.getDataState() == "1" && qhY02.getDataState() == "2") {
                            qhY02.setDataState(qhY04Vo.getDataState());
                            qhY02.setQualityOpinion(qhY04Vo.getQualityOpinion());
                            continue;
                        }
                    }
                } else {
                    if (qhY02.getDataState() == "1") {
                        //qhY02.setDataState("1");
                        qhY02.setQualityOpinion(qhY02.getQualityOpinion() + "Y04数据不能为空;");
                    } else {
                        qhY02.setDataState("1");
                        qhY02.setQualityOpinion("Y04数据不能为空;");
                    }
                }
                //Y05表
                List<QhY05Vo> qhY05VoList = qhY05Service.dataQualityCheck(drillId);
                if (!qhY05VoList.isEmpty() && qhY05VoList.size() > 0) {
                    for (QhY05Vo qhY05Vo : qhY05VoList) {
                        if (qhY05Vo.getDataState() == "1" && qhY02.getDataState() == "1") {
                            //qhY02.setDataState(qhY05Vo.getDataState());
                            qhY02.setQualityOpinion(qhY02.getQualityOpinion() + qhY05Vo.getQualityOpinion());
                            continue;
                        } else if (qhY05Vo.getDataState() == "1" && qhY02.getDataState() == "2") {
                            qhY02.setDataState(qhY05Vo.getDataState());
                            qhY02.setQualityOpinion(qhY05Vo.getQualityOpinion());
                            continue;
                        }
                    }
                }
                //Y06表
                List<QhY06Vo> qhY06VoList = qhY06Service.dataQualityCheck(drillId);
                if (!qhY06VoList.isEmpty() && qhY06VoList.size() > 0) {
                    for (QhY06Vo qhY06Vo : qhY06VoList) {
                        if (qhY06Vo.getDataState() == "1" && qhY02.getDataState() == "1") {
                            //qhY02.setDataState(qhY06Vo.getDataState());
                            qhY02.setQualityOpinion(qhY02.getQualityOpinion() + qhY06Vo.getQualityOpinion());
                            continue;
                        } else if (qhY06Vo.getDataState() == "1" && qhY02.getDataState() == "2") {
                            qhY02.setDataState(qhY06Vo.getDataState());
                            qhY02.setQualityOpinion(qhY06Vo.getQualityOpinion());
                            continue;
                        }
                    }
                } else {
                    if (qhY02.getDataState() == "1") {
                        //qhY02.setDataState("1");
                        qhY02.setQualityOpinion(qhY02.getQualityOpinion() + "Y06数据不能为空;");
                    } else {
                        qhY02.setDataState("1");
                        qhY02.setQualityOpinion("Y06数据不能为空;");
                    }
                }
                //Y08表
                List<QhY08Vo> qhY08VoList = qhY08Service.dataQualityCheck(drillId);
                if (!qhY08VoList.isEmpty() && qhY08VoList.size() > 0) {
                    for (QhY08Vo qhY08Vo : qhY08VoList) {
                        if (qhY08Vo.getDataState() == "1" && qhY02.getDataState() == "1") {
                            //qhY02.setDataState(qhY08Vo.getDataState());
                            qhY02.setQualityOpinion(qhY02.getQualityOpinion() + qhY08Vo.getQualityOpinion());
                            continue;
                        } else if (qhY08Vo.getDataState() == "1" && qhY02.getDataState() == "2") {
                            qhY02.setDataState(qhY08Vo.getDataState());
                            qhY02.setQualityOpinion(qhY08Vo.getQualityOpinion());
                            continue;
                        }
                    }
                }
                //Y18表
                QhY18Vo qhY18Vo = qhY18Service.dataQualityCheck(drillId);
                if (!PlatformObjectUtils.isEmpty(qhY18Vo)) {
                    if (qhY18Vo.getDataState() == "1" && qhY02.getDataState() == "1") {
                        //qhY02.setDataState(qhY18Vo.getDataState());
                        qhY02.setQualityOpinion(qhY02.getQualityOpinion() + qhY18Vo.getQualityOpinion());
                    } else if (qhY18Vo.getDataState() == "1" && qhY02.getDataState() == "2") {
                        qhY02.setDataState(qhY18Vo.getDataState());
                        qhY02.setQualityOpinion(qhY18Vo.getQualityOpinion());
                    }
                } else {
                    if (qhY02.getDataState() == "1") {
                        //qhY02.setDataState("1");
                        qhY02.setQualityOpinion(qhY02.getQualityOpinion() + "Y18数据不能为空;");
                    } else {
                        qhY02.setDataState("1");
                        qhY02.setQualityOpinion("Y18数据不能为空;");
                    }
                }
                this.updateQhY02(qhY02);
                if (qhY02.getDataState() == "1") {
                    drillSynthesizeCode = drillSynthesizeCode + "," + qhY02.getDrillSynthesizeCode();
                }
                //res.put("mag","综合钻孔编号:"+qhY02.getDrillSynthesizeCode()+","+qhY02.getQualityOpinion());
            }
        }
        if (!StringUtils.isEmpty(drillSynthesizeCode)) {
            drillSynthesizeCode = "综合钻孔编号:" + drillSynthesizeCode;
            res.put("mag", drillSynthesizeCode);
        }
        return res;
    }

    public QhY02Entity dataQualityCheck(QhY02Entity qhY02) {
        JSONObject res = new JSONObject();

        try {
            //检查字段值不为空
            StringBuilder errorMsg = new StringBuilder();
            Map<String, String> methods = new HashMap<>();
            setCheckFields(methods);

            ServerUtil.checkFieldNull(qhY02, methods, errorMsg);

            if (errorMsg.length() > 0 || org.apache.commons.lang3.StringUtils.isNotEmpty(errorMsg.toString())) {
                qhY02.setQualityOpinion("Y02的" + errorMsg.toString());
                qhY02.setDataState("1");
                return qhY02;
            }
            //检查字段属性
            if (qhY02.getLongitude().length() - qhY02.getLongitude().indexOf(".") - 1 < 4) {
                ServerUtil.addErrorMsg(errorMsg, "孔位经度", "小数点后保留至少4位");
            }
            if (qhY02.getLatitude().length() - qhY02.getLatitude().indexOf(".") - 1 < 4) {
                ServerUtil.addErrorMsg(errorMsg, "孔位纬度", "小数点后保留至少4位");
            }
            String drillSynthesizeCode = qhY02.getDrillSynthesizeCode();
            Double longitude = Double.parseDouble(qhY02.getLongitude());
            Double latitude = Double.parseDouble(qhY02.getLatitude());
            Double drillDepth = qhY02.getDrillDepth();

            if (!(drillSynthesizeCode.length() == 12)) {
                ServerUtil.addErrorMsg(errorMsg, "钻孔综合编号", "不符合规范");
            } else {
                String str = drillSynthesizeCode.substring(6, 8);
                if (!("SK".equals(str) || "PK".equals(str))) {
                    ServerUtil.addErrorMsg(errorMsg, "钻孔综合编号", "不符合规范");
                }
            }
            if (longitude < 73.0000 || longitude > 136.0000) {
                ServerUtil.addErrorMsg(errorMsg, "孔位经度", "73.0000~136.0000之间");
            }
            if (latitude < 5.0000 || latitude > 54.0000) {
                ServerUtil.addErrorMsg(errorMsg, "孔位纬度", "5.0000~54.0000之间");
            }
            if (drillDepth < 0) {
                ServerUtil.addErrorMsg(errorMsg, "钻孔深度", "大于0");
            }

            String strErrorMsg = errorMsg.toString();
            if (!strErrorMsg.isEmpty()) {
                qhY02.setQualityOpinion("Y02的" + strErrorMsg);
                qhY02.setDataState("1");
            } else {
                qhY02.setQualityOpinion("系统自动质检通过");
                qhY02.setDataState("2");
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return qhY02;
    }

    private void setCheckFields(Map<String, String> methods) {
        methods.put("drillSynthesizeCode", "钻孔综合编号");
        methods.put("drillDependProject", "钻孔依托的项目");
        methods.put("projectCompleteInstitution", "项目完成单位");
        methods.put("projectCompleteDate", "项目完成时间");
        methods.put("projectPrincipal", "项目负责人");
        methods.put("drillConstructionInstitution", "钻孔勘察单位");
        methods.put("drillConstructionPrincipal", "钻孔勘察负责人");
        methods.put("constructionStartDate", "勘察施工日期");
        methods.put("constructionReportDate", "勘察报告日期");
        methods.put("drillCode", "钻孔编号");
        methods.put("longitude", "孔位经度（°）");
        methods.put("latitude", "孔位纬度（°）");
        methods.put("drillDepth", "钻孔深度");
        methods.put("elevation", "地面高程");
        methods.put("province", "钻孔所在省级行政区");
        methods.put("city", "钻孔所在地市级行政区");
        methods.put("area", "钻孔所在县级行政区");
        methods.put("village", "钻孔所在乡级行政区");
        methods.put("accessory", "附件");
    }

    @Override
    public JSONObject checkCoordinate(String ids) {
        List<String> errorIds = new ArrayList<>();
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhY02Entity> qhY02List = this.qhY02Repository.findAllById(idList);
        if (!PlatformObjectUtils.isEmpty(qhY02List) && qhY02List.size() > 0) {
            for (QhY02Entity qhY02 : qhY02List) {
                double lon = Double.parseDouble(qhY02.getLongitude());
                double lat = Double.parseDouble(qhY02.getLatitude());
                String province = qhY02.getProvince();
                String city = qhY02.getCity();
                String area = qhY02.getArea();
                //校验
                if ((lon < 73.0000 || lon > 136.0000) || (lat < 5.0000 || lat > 54.0000)) {
                    errorIds.add(qhY02.getId());
                    continue;
                }
                Map<String, String> coordRes = LocationUtil.getLocationInfoByTD(lon, lat);
                if (!province.equals(coordRes.get("province")) ||
                        !city.equals(coordRes.get("city")) ||
                        !area.equals(coordRes.get("county"))) {
                    errorIds.add(qhY02.getId());
                }
            }
        }
        JSONObject json = new JSONObject();
        json.put("data", errorIds);
        if (errorIds.size() > 0) {
            json.put("message", "共" + errorIds.size() + "条数据校验未通过");
        } else {
            json.put("message", "数据校验通过");
        }
        return json;
    }

    @Override
    public void exportData(HttpServletResponse response,String userId) {//筛选项 筛选人员权限 省对应省 县对应县
        DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);

        try {
            String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String name = dateStr+mainDept.getDeptName() + "统计分析数据.xlsx";
            //response.setContentType("application/octet-stream ");
//            response.setHeader("content-Type", "application/vnd.ms-excel");
//            response.setHeader("Connection", "close"); // 表示不能用浏览器直接打开
//            //response.setHeader("Accept-Ranges", "bytes");// 告诉客户端允许断点续传多线程连接下载
//            response.setHeader("Content-Disposition", "attachment;fileName="
//                    + new String(name.getBytes("GB2312"), "ISO8859-1"));
//            response.setCharacterEncoding("UTF-8");

            response.setContentType("application/octet-stream ");
            response.setHeader("Connection", "close"); // 表示不能用浏览器直接打开
            response.setHeader("Accept-Ranges", "bytes");// 告诉客户端允许断点续传多线程连接下载
           // response.setHeader("Content-Disposition",
              //      "attachment;filename=" + new String(name.getBytes("GB2312"), "ISO8859-1"));
            response.setCharacterEncoding("UTF-8");

            response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(name,"UTF-8"));

            //HSSFWorkbook workbook = new HSSFWorkbook();// 创建一个Excel文件
            Workbook workbook = new XSSFWorkbook();// 创建一个Excel文件
            // 样式设置
            CellStyle columnHeadStyle = workbook.createCellStyle();
            columnHeadStyle.setFillPattern(FillPatternType.NO_FILL); // 背景
            columnHeadStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex()); // 背景色AQUA.getIndex()
            columnHeadStyle.setBorderBottom(BorderStyle.THIN); // 下边框
            columnHeadStyle.setBorderLeft(BorderStyle.THIN);// 左边框
            columnHeadStyle.setBorderTop(BorderStyle.THIN);// 上边框
            columnHeadStyle.setBorderRight(BorderStyle.THIN);// 右边框
            columnHeadStyle.setAlignment(HorizontalAlignment.LEFT);//左右居中
            columnHeadStyle.setVerticalAlignment(VerticalAlignment.BOTTOM);// 上下居中
            columnHeadStyle.setWrapText(true);//自动换行

            Sheet sheet = workbook.createSheet("统计分析数据");
            sheet.setColumnWidth(0, 6000);
            String[] sheetHeadTitle = new String[]{"省份", "PK", "SK"};
            ConvertUtils.register(new DateConverter(null), java.util.Date.class);
            int sumPK = 0;
            int sumSK = 0;
            List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
            //是否为超级管理员
            boolean containtRole = ServerUtil.isContaintRole(roles, "zfzxqhadmin");
            if (containtRole) {
                List<String> divisionNames = baseDivisionRepository.findDivisionNames();
                List<ExportVo> sumPKList = myQhRepository.getSumList("%PK%");
                List<ExportVo> sumSKList = myQhRepository.getSumList("%SK%");
                for (int i = 0; i < divisionNames.size() + 2; i++) {
                    Row row0 = sheet.createRow(i);
                    row0.setHeightInPoints(30);

                    for (int t = 0; t < sheetHeadTitle.length; t++) {
                        Cell cel0_1 = row0.createCell(t);
                        if (i == 0) {
                            cel0_1.setCellValue(new XSSFRichTextString(sheetHeadTitle[t]));
                        } else {
                            if (i == divisionNames.size() + 1) {
                                if (t == 0) {
                                    cel0_1.setCellValue(new XSSFRichTextString("总和"));
                                } else if (t == 1) {
                                    cel0_1.setCellValue(new XSSFRichTextString(String.valueOf(sumPK)));
                                } else if (t == 2) {
                                    cel0_1.setCellValue(new XSSFRichTextString(String.valueOf(sumSK)));
                                }
                            } else {
                                String province = divisionNames.get(i - 1);
                                Integer sumCode = 0;
                                if (t == 0) {
                                    cel0_1.setCellValue(new XSSFRichTextString(province));
                                } else {
                                    if (t == 1) {
                                        for (ExportVo vo : sumPKList) {
                                            if (province.equals(vo.getProvince())) {
                                                sumCode = vo.getSumCode();
                                                if (sumCode == null) {
                                                    sumCode = 0;
                                                }
                                                sumPK = sumPK + sumCode;
                                                break;
                                            }
                                        }
                                    } else if (t == 2) {
                                        for (ExportVo vo : sumSKList) {
                                            if (province.equals(vo.getProvince())) {
                                                sumCode = vo.getSumCode();
                                                if (sumCode == null) {
                                                    sumCode = 0;
                                                }
                                                sumSK = sumSK + sumCode;
                                                break;
                                            }
                                        }
                                    }
                                    cel0_1.setCellValue(new XSSFRichTextString(String.valueOf(sumCode)));
                                }
                            }
                        }
                        cel0_1.setCellStyle(columnHeadStyle);
                    }
                    // sheet.autoSizeColumn((short) i);
                }
            } else {
                List<QhY02Entity> qhY02Entities = qhY02NativeRepository.listQhY02s(new QhY02QueryParams());
                for (QhY02Entity qhY02Entity : qhY02Entities) {
                    String drillSynthesizeCode = qhY02Entity.getDrillSynthesizeCode();
                    if (drillSynthesizeCode.contains("PK")) {
                        sumPK++;
                    } else if (drillSynthesizeCode.contains("SK")) {
                        sumSK++;
                    }
                }
                for (int i = 0; i < 1 + 1; i++) {
                    Row row0 = sheet.createRow(i);
                    row0.setHeightInPoints(30);
                    for (int t = 0; t < sheetHeadTitle.length; t++) {
                        Cell cel0_1 = row0.createCell(t);
                        if (i == 0) {
                            cel0_1.setCellValue(new XSSFRichTextString(sheetHeadTitle[t]));
                        } else {
                            String divisionName = mainDept.getDeptName();
                            if (t == 0) {
                                cel0_1.setCellValue(new XSSFRichTextString(divisionName));
                            } else {
                                if (t == 1) {
                                    cel0_1.setCellValue(new XSSFRichTextString(String.valueOf(sumPK)));
                                } else if (t == 2) {
                                    cel0_1.setCellValue(new XSSFRichTextString(String.valueOf(sumSK)));
                                }
                            }
                        }
                        cel0_1.setCellStyle(columnHeadStyle);
                    }
                    // sheet.autoSizeColumn((short) i);
                }
            }

            OutputStream out = response.getOutputStream();
            workbook.write(out);
            // ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // workbook.write(bos);
            // bos.writeTo(out);
            if (out != null) {
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
